package no.ntnu.idi.deid.patternmatching.search.dictionary.medicalcodes;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;

import no.ntnu.idi.deid.config.FilePaths;
import no.ntnu.idi.deid.documentunits.Token;
import no.ntnu.idi.deid.searchresultunits.CategoryTag;
import no.ntnu.idi.deid.searchresultunits.Tag;

public class NCMP_Codes {
	
	private static Map<String, String> NCMPCodes;
	
	private NCMP_Codes() {
		if(NCMPCodes==null){
			try {
				readAndMakeNCMPCodes();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	private void readAndMakeNCMPCodes() throws FileNotFoundException{
		NCMPCodes = new HashMap<String,String>();
		Scanner sc = new Scanner(new File(FilePaths.getNCMPCodesPath()));
		while(sc.hasNext()){
			String line = sc.nextLine().trim().toLowerCase();
			if(!line.trim().isEmpty()){handleLine(line);}
		}
		sc.close();
	}
	
	private void handleLine(String line){
		if(line.contains("$$")){
			String[] split = line.split("\\$\\$");
			String code = split[0].trim();
			String description = split[1].trim();
			NCMPCodes.put(code, description);
		}
	}
	
	//***************************SEARCH****************************//
	
	private static String replaceAllSpecialCharsFromNCMPCode(String code){
		return code.replaceAll("[^a-zA-Z_0-9]", "");
	}
	
	public static CategoryTag searchNCMPCode(String code){
		code = code.toLowerCase();
		new NCMP_Codes();
		if(NCMPCodes.containsKey(replaceAllSpecialCharsFromNCMPCode(code))){
			CategoryTag resultTag = new CategoryTag(Tag.NCMP);
			resultTag.setValues(replaceAllSpecialCharsFromNCMPCode(code), NCMPCodes.get(replaceAllSpecialCharsFromNCMPCode(code)));
			return resultTag;
		}
		return null;
	}
	
	public static CategoryTag searchNCMPCode(Token token){
		return searchNCMPCode(token.getStripped());
	}
	
	public static CategoryTag searchExactNCMPDescription(String searchString){
		searchString = searchString.toLowerCase();
		new NCMP_Codes();
		if(NCMPCodes.containsValue(searchString.trim())){
			Iterator<Entry<String, String>> it = NCMPCodes.entrySet().iterator();
			while(it.hasNext()){
				Entry<String, String> entry = (Entry<String, String>) it.next();
				if(entry.getValue().equals(searchString.trim())){
					CategoryTag resultTag = new CategoryTag(Tag.NCMP);
					resultTag.setValues(entry.getKey(), searchString);
					return resultTag;
				}
			}
		}
		return null;
	}
}
